package com.letv.common;

import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Paths;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.letv.util.SQLUtil;

public class ConnectionManager {

    private final static Logger logger = LoggerFactory.getLogger(ConnectionManager.class);
    private static ConnectionManager instance = new ConnectionManager();

    public static ConnectionManager getInstance() {
        return instance;
    }

    private Map<String, DataSource> dataSourceMap = new HashMap<>();

    private ConnectionManager() {
        initDataSource("local");
        initDataSource("leso");
        initDataSource("mms");
    }

    private void initDataSource(String name) {

        Properties props = new Properties();
        try {
            String propsPath = Paths.get(Constants.WEB_PATH, "WEB-INF", "classes", name + ".dbcp.properties").toString();
//            String propsPath = "E:\\code\\shouye\\search_java\\offline_task\\trunk\\target\\ROOT\\WEB-INF\\classes\\" + name + ".dbcp.properties";
            props.load(new FileReader(propsPath));
        } catch (IOException e) {
            logger.error("Failed to load data source properties:" + name, e);
            return;
        }
        logger.info("Data source {} properties: {}", name, props);
        DataSource ds = null;
        try {
            ds = BasicDataSourceFactory.createDataSource(props);
        } catch (Exception e) {
            logger.error("Failed to create data source " + name, e);
            return;
        }
        dataSourceMap.put(name, ds);
    }

    private Connection getConnection(String type) {

        DataSource ds = dataSourceMap.get(type);
        Connection connection = null;
        try {
            connection = ds.getConnection();
        } catch (Exception e) {
            logger.error("ds getConnection() error! ", e);
            SQLUtil.close(connection);
        }
        return connection;
    }

    /****
     * 取得本地搜索数据库连接
     * 
     * @return
     */
    public Connection getConnection() {
        return getConnection("local");
    }

    /****
     * 取得新媒资数据库连接
     * 
     * @return
     */
    public Connection getConnectionFromMMS() {
        return getConnection("mms");
    }

    /****
     * 取得站外数据源数据库连接
     * 
     * @return
     */
    public Connection getConnectionFromLeso() {
        return getConnection("leso");
    }
}
